const fs = require('fs');
const path = require('path');

class EntityScaner{

    constructor(){
        this.root = ""
        this.entities = [] 
        this.scanPath = []
        this.filterFn = function( _fileName ){
            return _fileName.indexOf("_") == 0 ;
        }
    }
    
    setNextPath( next_path ){
        // if( next_path )
        //     this.scanPath.push( path.join( this.root, next_path ) )
        this.scanPath.push( next_path )
    }

    setFilter( fn ){
        this.filterFn = fn 
    }

    isFile( filePath ) {
        return fs.statSync( filePath ).isFile()
    }

    scanTask( nextPath ){
        const files = fs.readdirSync( nextPath )
        files
        // .filter(file => file.endsWith('.js'))
        .forEach( file_name => {
            // const file_name = file.substr(0, file.length - 3)
            const filePath = path.join( nextPath , file_name ) 
            if( this.isFile(filePath) && file_name.endsWith(".js") ){
                if( this.filterFn( file_name ) == false ){
                    const file_entity = require( filePath )
                    file_entity.__nickname = file_name 
                    file_entity.__path = filePath
                    this.entities.push( file_entity ) 
                }   
            }else{
               this.scanPath.push( filePath )
            }
        })
    }
    
    scan(){
        this.entities = [] // clear.
        while( true ){
            const nextPath = this.scanPath.pop()
            if( !nextPath )
                break 
            this.scanTask( nextPath )
        }
        return this.entities 
    }

    getEntities() {
        return this.entities 
    }

}

module.exports = EntityScaner
